<?php
namespace app\wx\model;
use app\wx\model\Cdb;
use think\Db;

class Reg
{

    /**
     * @param $app = 应用的名称字符串，例如 ams mss
     * @param array $array 传入数据为model('Qywx')->get_permanent_code()的返回json字符串json_decode后的数组
     * @return array
     */
    function add_company($app, $array=array())
    {
        if(empty($array))
        {
            return ['res'=>false,'meg'=>'传入参数错误'];
        }
        $company=Db::name('company')->field('id')->where('corpid',$array['auth_corp_info']['corpid'])->find();


        $save_data['is_use']=1;
        $save_data['corp_name']=$array['auth_corp_info']['corp_name'];
        $save_data['corp_type']=$array['auth_corp_info']['corp_type'];
        $save_data['corp_square_logo_url']=$array['auth_corp_info']['corp_square_logo_url'];
        $save_data['corp_user_max']=$array['auth_corp_info']['corp_user_max'];
        $save_data['corp_full_name']=$array['auth_corp_info']['corp_full_name'];
        $save_data['subject_type']=$array['auth_corp_info']['subject_type'];
        $save_data['subject_type']=$array['auth_corp_info']['subject_type'];
        $save_data['subject_type']=$array['auth_corp_info']['verified_end_time'];
        $save_data['corp_wxqrcode']=$array['auth_corp_info']['corp_wxqrcode'];
        $save_data['corpid']=$array['auth_corp_info']['corpid'];
        $save_data['userid']=$array['auth_user_info']['userid'];
        $save_data['name']=$array['auth_user_info']['name'];
        $save_data['mobile']=$array['auth_user_info']['mobile'];
        $save_data['avatar']=$array['auth_user_info']['avatar'];
        $save_data['email']=$array['auth_user_info']['email'];
        $save_data['add_time']=time();

        $app_data['app']=$app;
        $app_data['agentid']=$array['auth_info']['agent'][0]['agentid'];
        $app_data['name']=$array['auth_info']['agent'][0]['name'];
        $app_data['corpid']=$array['auth_corp_info']['corpid'];
        $app_data['permanent_code']=$array['permanent_code'];

        $company_app=Db::name('company_app')->where(['app'=>$app,'corpid'=>$app_data['corpid']])->find();
        if($company_app['id']=='')
        {
            Db::name('company_app')->insert($app_data);
        }else{
            Db::name('company_app')->where('id',$company_app['id'])->update($save_data);
        }

        if($company['id']=='')
        {
            $res=Db::name('company')->insert($save_data);
            if($res!=false)
            {
                return ['res'=>true,'meg'=>'企业授权成功'];
            }else{
                return ['res'=>false,'meg'=>'写入企业数据失败'];
            }
        }else{
            Db::name('company')->where('id',$company['id'])->update($save_data);
            return ['res'=>true,'meg'=>'企业重新授权'];
        }
    }
    //企业取消授权,$coprid为授权企业cropid
    function cancel_company($corpid='')
    {
        /*
        if($corpid=='')
        {
            return ['res'=>false,'meg'=>'传入数据不能为空'];
        }
        $company=db('company')->field('id,is_use')->where('corpid',$corpid)->find();
        if($company['id']=='')
        {
            return ['res'=>false,'meg'=>'企业不存在'];
        }else{
            $res=db('company')->where('id',$company['id'])->update(['is_use'=>0,'stop_time'=>time()]);
            if($res!==false)
            {
                return ['res'=>true,'meg'=>'取消授权成功'];
            }else{
                return ['res'=>false,'meg'=>'数据库操作错误'];
            }
        }*/
    }

    /**
     * @param $app 应用字符串，例如ams mss
     * @param string $corpid 使用企业corpid
     * @return array
     */
    function company_start($app='', $corpid='')
    {
        if($app=='')
        {
            return ['res'=>3,'msg'=>'企业不存在,请重新注册'];
        }
        $com=Db::name('company')->where('corpid',$corpid)->find();
        if($com['id']=='')
        {
            return ['res'=>2,'msg'=>'企业不存在,请重新注册'];
        }
        if($com['is_start']=='1')
        {
            return ['res'=>1,'msg'=>'企业已经初始化，跳转到后台管理页面'];
        }

        //同步部门信息开始
        $res=$this->copy_wx_dept($app,$com['corpid']);
        if($res==false)
        {
            return ['res'=>3,'msg'=>'同步企业部门失败'];
        }
        //同步用户信息开始
        $res=$this->copy_wx_user($app,$com['corpid']);
        if($res==false)
        {
            return ['res'=>4,'msg'=>'同步企业用户失败'];
        }


        //$auth=model('Qywx')->get_auth_info($com['permanent_code'],$com['corpid']);
        db('company')->where('corpid',$com['corpid'])->update(['is_start'=>1]);
    }

    //同步企业部门信息,删除原有数据重新同步
    function copy_wx_dept($app='',$corpid='')
    {
        if($corpid=='')
        {
            return false;
        }
        //获取部门列表
        $res=model('Qywx')->get_dept_list($app,$corpid);
        if($res==false)
        {
            return false;
        }
        $dept_list=json_decode($res,true);
        foreach($dept_list['department'] as $k=>$v)
        {
            $new_dept_list[$k]['dept_id']=$v['id'];
            $new_dept_list[$k]['name']=$v['name'];
            $new_dept_list[$k]['parentid']=$v['parentid'];
            $new_dept_list[$k]['sort']=$v['order'];
        }
        $db=Cdb::db($corpid);
        $db->name('dept')->where('dept_id','>=',0)->delete();
        $db->name('dept')->insertAll($new_dept_list);
        return true;
    }

    //同步企业用户信息，删除原有用户user表，重新导入，仅第一次初始化使用
    function copy_wx_user($app='',$corpid='')
    {
        if($corpid=='')
        {
            return false;
        }

        //获取根部门其下所有子部门的用户列表
        $res=model('Qywx')->get_user_list($app,$corpid,1,1);
        if($res==false)
        {
            return false;
        }
        $user_list=json_decode($res,true);
        $add_time=time();
        $i=0;
        foreach ($user_list['userlist'] as $k=>$v)
        {

            foreach($v['department'] as $d)
            {
                $user_dept[$i]['userid']=$v['userid'];
                $user_dept[$i]['dept_id']=$d;
                $i++;
            }
            $new_user_list[$k]['userid']=$v['userid'];
            $new_user_list[$k]['name']=$v['name'];
            $dept_id=implode(',',$v['department']);
            $new_user_list[$k]['dept']=$dept_id;
            $new_user_list[$k]['position']=$v['position'];
            $new_user_list[$k]['mobile']=$v['mobile'];
            $new_user_list[$k]['gender']=$v['gender'];
            $new_user_list[$k]['email']=$v['email'];
            $new_user_list[$k]['isleader']=$v['isleader'];
            $new_user_list[$k]['avatar']=$v['avatar'];
            $new_user_list[$k]['telephone']=$v['telephone'];
            $new_user_list[$k]['english_name']=$v['english_name'];
            $new_user_list[$k]['status']=$v['status'];
            $new_user_list[$k]['add_time']=$add_time;
            $i++;
        }
        $db=Cdb::db($corpid);

        $db->name('user')->where('userid','<>','')->delete();
        $db->name('user')->insertAll($new_user_list);

        $db->name('user_dept')->where('userid','<>','')->delete();
        $db->name('user_dept')->insertAll($user_dept);
        return true;
    }

    //创建用户成员
    /*
     * $xml 企业微信推送解密后的xml字符串
     * */
    function create_user($str='')
    {
        $xml = new \DOMDocument();
        $xml->loadXML($str);
        $corpid=$xml->getElementsByTagName('AuthCorpId')->item(0)->nodeValue;
        $com=db('company')->where('corpid',$corpid)->find();
        if($com['id']=='')
        {
            return false;
        }
        $db=Cdb::db($corpid);
        $data['userid']=$xml->getElementsByTagName('UserID')->item(0)->nodeValue;

        $user=$db->name('user')->where('userid',$data['userid'])->find();
        if($user['id']!='')
        {
            return false;
        }
        $name=$xml->getElementsByTagName('Name')->item(0)->nodeValue;
        if($name!='')
        {
            $data['name']=$name;
        }
        $gender=$xml->getElementsByTagName('Gender')->item(0)->nodeValue;
        if($gender!='')
        {
            $data['gender']=$gender;
        }
        $avatar=$xml->getElementsByTagName('Avatar')->item(0)->nodeValue;
        if($avatar!='')
        {
            $data['avatar']=$avatar;
        }
        $dept=$xml->getElementsByTagName('Department')->item(0)->nodeValue;
        if($dept!='')
        {
            $data['dept']=$dept;
            $dept=explode(',',$dept);
            foreach ($dept as $k=>$d)
            {
                $user_dept[$k]['userid']=$data['userid'];
                $user_dept[$k]['dept_id']=$d;
            }
            $db->name('user_dept')->where('userid',$data['userid'])->delete();
            $db->name('user_dept')->insertAll($user_dept);
        }
        $position=$xml->getElementsByTagName('Position')->item(0)->nodeValue;
        if($position!='')
        {
            $data['position']=$position;
        }
        $IsLeader=$xml->getElementsByTagName('IsLeader')->item(0)->nodeValue;
        if($IsLeader!='')
        {
            $data['isleader']=$IsLeader;
        }
        $english_name=$xml->getElementsByTagName('EnglishName')->item(0)->nodeValue;
        if($english_name!='')
        {
            $data['english_name']=$english_name;
        }
        $data['add_time']=time();
        $err=json_encode($data);
        Db::name('error')->insert(['content'=>$err]);
        return $db->name('user')->insert($data);

    }

    //更新用户成员
    /*
     * $xml 企业微信推送解密后的xml字符串
     * */
    function update_user($str='')
    {
        $xml = new \DOMDocument();
        $xml->loadXML($str);
        $corpid=$xml->getElementsByTagName('AuthCorpId')->item(0)->nodeValue;
        $com=db('company')->where('corpid',$corpid)->find();
        if($com['id']=='')
        {
            return false;
        }
        $db=Cdb::db($corpid);
        $userid=$xml->getElementsByTagName('UserID')->item(0)->nodeValue;
        $dept_userid=$userid;
        $NewUserID=$xml->getElementsByTagName('NewUserID')->item(0)->nodeValue;
        if($NewUserID!='')
        {
            $data['userid']=$NewUserID;
            $data['old_userid']=$userid;
            $dept_userid=$NewUserID;
            //变更当前所有跟此用户绑定的信息

        }

        $name=$xml->getElementsByTagName('Name')->item(0)->nodeValue;
        if($name!='')
        {
            $data['name']=$name;
        }
        $english_name=$xml->getElementsByTagName('EnglishName')->item(0)->nodeValue;
        if($english_name!='')
        {
            $data['english_name']=$english_name;
        }
        $dept=$xml->getElementsByTagName('Department')->item(0)->nodeValue;
        if($dept!='')
        {
            $data['dept']=$dept;
            $dept=explode(',',$dept);
            foreach ($dept as $k=>$d)
            {
                $user_dept[$k]['userid']=$dept_userid;
                $user_dept[$k]['dept_id']=$d;
            }
            $db->name('user_dept')->where('userid',$userid)->delete();
            $db->name('user_dept')->insertAll($user_dept);
        }
        $mobile=$xml->getElementsByTagName('Mobile')->item(0)->nodeValue;
        if($mobile!='')
        {
            $data['mobile']=$mobile;
        }
        $position=$xml->getElementsByTagName('Position')->item(0)->nodeValue;
        if($position!='')
        {
            $data['position']=$position;
        }
        $gender=$xml->getElementsByTagName('Gender')->item(0)->nodeValue;
        if($gender!='')
        {
            $data['gender']=$gender;
        }
        $email=$xml->getElementsByTagName('Email')->item(0)->nodeValue;
        if($email!='')
        {
            $data['email']=$email;
        }
        $avatar=$xml->getElementsByTagName('Avatar')->item(0)->nodeValue;
        if($avatar!='')
        {
            $data['avatar']=$avatar;
        }
        $telephone=$xml->getElementsByTagName('Telephone')->item(0)->nodeValue;
        if($telephone!='')
        {
            $data['telephone']=$telephone;
        }
        $status=$xml->getElementsByTagName('Status')->item(0)->nodeValue;
        if($status!='')
        {
            $data['status']=$status;
        }
        $isleader=$xml->getElementsByTagName('IsLeader')->item(0)->nodeValue;
        if($isleader!='')
        {
            $data['isleader']=$isleader;
        }

        return $db->name('user')->where('userid',$userid)->update($data);

    }

    //删除成员
    /*
     * $xml 企业微信推送解密后的xml字符串
     * */
    function delete_user($str='')
    {
        $xml = new \DOMDocument();
        $xml->loadXML($str);
        $corpid=$xml->getElementsByTagName('AuthCorpId')->item(0)->nodeValue;
        $com=db('company')->where('corpid',$corpid)->find();
        if($com['id']=='')
        {
            return false;
        }
        $userid=$xml->getElementsByTagName('UserID')->item(0)->nodeValue;
        $db=Cdb::db($corpid);
        $db->name('user_dept')->where('userid',$userid)->delete();
        return $db->name('user')->where('userid',$userid)->delete();

    }

}